package com.wang.mvchain.web.springmvc.interceptor;

import java.net.URLEncoder;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.codec.digest.HmacAlgorithms;
import org.apache.commons.codec.digest.HmacUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wang.mvchain.common.controller.BaseController;
import com.wang.mvchain.common.util.ConstatFinalUtil;
import com.wang.mvchain.users.pojo.AUsers;
import com.wang.mvchain.users.service.IUsersService;

@Component("usersAuthInterceptor")
public class UsersAuthInterceptor extends BaseController implements HandlerInterceptor
{
	@Resource
	private IUsersService usersService;
	/* 请求的Url */
	private String verifyURL = ConstatFinalUtil.SYS_BUNDLE.getString("sso.users.verifyurl");
	/* 私钥 */
	private String usersCenterOuterPriKey = "wangshUsersCenter2019";
	
	/**
	 * 方法执行之后执行
	 */
	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object arg2, Exception exception)
			throws Exception
	{
		// ConstatFinalUtil.SYS_LOG.info("----3 afterCompletion(执行之后执行) ----");
	}

	/**
	 * 请求完成返回视图时调用
	 */
	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object arg2, ModelAndView mv)
			throws Exception
	{
		// ConstatFinalUtil.SYS_LOG.info("----2 postHandle(请求完成返回视图时调用) ----");
	}

	/**
	 * 方法执行之前执行
	 */
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object obj) throws Exception
	{
		String info = "" ;
		
		HttpSession session = request.getSession();
		AUsers users = (AUsers) session.getAttribute("users");
		
		if(users != null)
		{
			return true ; 
		}
		
		//ConstatFinalUtil.SYS_LOG.info("----1 preHandle(执行之后执行) ----");
		String[] tokens = request.getParameterValues("token");
		String token = "" ; 
		if(tokens != null && tokens.length > 0)
		{
			token = tokens[tokens.length - 1]; 
		}
		Map<String, String> paramsMap = new HashMap<String, String>();
		if(users == null && !"".equalsIgnoreCase(token))
		{
			try
			{
				/*
				 * 拼装上行的json
				 */
				/* 拼装上行信息 */
				JSONObject reqJSON = new JSONObject() ; 
				reqJSON.put("version", "1");
				reqJSON.put("method", "verifyUsersToken");
				reqJSON.put("pubKey", UUID.randomUUID().toString());
				reqJSON.put("time", System.currentTimeMillis() + "");
				
				/* 加密 */
				/* sha256,key加密 */
				HmacUtils hmacUtils = new HmacUtils(HmacAlgorithms.HMAC_SHA_256, usersCenterOuterPriKey);
				/* 原字符串 */
				String souStr = reqJSON.getString("version") + 
						reqJSON.getString("pubKey") + reqJSON.getString("time") ; 
				/* 加密 */
				String encrypt = hmacUtils.hmacHex(souStr);
				reqJSON.put("encrypt", encrypt);
				
				JSONObject dataJSON = new JSONObject();
				dataJSON.put("token", token);
				reqJSON.put("data", dataJSON);
				
				paramsMap.put("json", reqJSON.toJSONString());
				paramsMap.put("requestURL", verifyURL);
				/* 请求对方服务器 */
				String responseStr = httpUtil.methodPost(Collections.EMPTY_MAP , paramsMap);
				
				JSONObject responseJSON = (JSONObject) JSON.parse(responseStr);
				if(responseJSON != null && "0".equalsIgnoreCase(responseJSON.get("code") + ""))
				{
					//登陆成功
					JSONObject dataResJSON = (JSONObject) responseJSON.get("data");
					JSONObject usersJSON = dataResJSON.getJSONObject("users");
					String id = usersJSON.get("id") + "";
					String email = usersJSON.get("email") + "";
					
					Map<String, Object> condMap = new HashMap<String, Object>();
					condMap.put("ssoid", id);
					users = this.usersService.findOneUsersService(condMap);
					
					if(users != null)
					{
						users.setEmail(email);
						users.setSsoid(Integer.valueOf(id));
						users.setUpdatetime(new Date());
						//将令牌放到对象之中
						users.setTicketStr(token);
						
						this.usersService.updateOneUsersService(users);
					}else
					{
						users = new AUsers();
						users.setEmail(email);
						users.setStatus(Byte.valueOf("1"));
						users.setSsoid(Integer.valueOf(id));
						users.setCreatetime(new Date());
						users.setUpdatetime(new Date());
						//将令牌放到对象之中
						users.setTicketStr(token);
						
						JSONObject resultDbJSON = this.usersService.saveOneUsersService(users);
						/*if(Integer.valueOf(resultDbJSON.get("code") + "") > 0 )
						{
							users.setId(Integer.valueOf(resultDbJSON.get("code") + ""));
						}*/
					}
					
					session.setAttribute("users", users);
					return true ; 
				}
			} catch (Exception e)
			{
				ConstatFinalUtil.SYS_LOG.error("验证登陆信息出错了:", e);
			}
		}
		
		//ConstatFinalUtil.SYS_LOG.info(request.getRequestURL() + "----->getRequestURI:" + request.getRequestURI());
		//拼装当前访问的url
		String queryStr = request.getQueryString() == null ? "" : request.getQueryString();
		String currUrl = request.getRequestURL() + "";
		if(!"".equalsIgnoreCase(queryStr))
		{
			currUrl += "?" + queryStr ;
		}
		currUrl = URLEncoder.encode(currUrl, "UTF-8");
		String url = ConstatFinalUtil.SYS_BUNDLE.getString("sso.users.main");
		url += "&returnUrl=" +  currUrl ; 
		
		response.sendRedirect(url);
		//未登陆
		return false ; 
	}
}
